package com.example.lotterysystem.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.apache.ibatis.annotations.Insert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    /**
     * 密钥: Base64 编码的密钥
     */
    private static final String SECRET = "AYoxORAwM8qsk+ex4eL2Rasxhi/6s1kf3vE9C9yF7bc=";

    /**
     * 生成安全密钥: 将一个Base64编码的密钥解码并创建一个HMAC SHA密钥
     */
    private static final SecretKey SECRETY_KEY = Keys.hmacShaKeyFor(
            Decoders.BASE64.decode(SECRET)
    );

    /**
     * 过期时间 (毫秒)
     */
    private static final long EXPIRATION = 60 * 60 * 1000 * 100;


    /**
     * 生成token
     */
    public static String genJwt(Map<String, Object> claim) {
        //签名算法
        String token = Jwts.builder()
                .setClaims(claim)            //自定义内容(载荷)
                .setIssuedAt(new Date())    //设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION)) //设置过期时间
                .signWith(SECRETY_KEY)      //签名算法
                .compact();
        return token;
    }

    /**
     * 验证密钥
     */
    public static Claims parseJWT(String token) {
        if(!StringUtils.hasLength(token)) {
            return null;
        }
        //创建解析器, 设置签名密钥
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(SECRETY_KEY);
        Claims claims = null;
        try {
            //解析token
            claims = jwtParserBuilder.build().parseClaimsJws(token).getBody();
        }catch (Exception e) {
            logger.error("解析令牌错误, token:{}", token, e);
        }
        return claims;
    }

    /**
     * 从token中获取用户ID
     */
    public static Integer getUserIdFromToken(String jwtToken) {
        Claims claims = JWTUtil.parseJWT(jwtToken);
        if(claims != null) {
            Map<String, Object> userInfo = new HashMap<>(claims);
            return (Integer) userInfo.get("userId");
        }
        return null;
    }

//    //生成密钥
//    public static void genKey() {
//        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//        String str = Encoders.BASE64.encode(secretKey.getEncoded());
//        System.out.println(str);
//    }

//    public static void main(String[] args) {
//        genKey();
//    }

}
